//
//  TIMChatViewController.m
//  NCChatUI_Example
//
//  Created by LINAICAI on 2018/4/16.
//  Copyright © 2018年 LINAICAI. All rights reserved.
//

#import "TIMChatViewController.h"
#import "TIMChatData.h"
#import <Masonry.h>
#import <NCChatUserInfoManager.h>
@interface TIMChatViewController ()
@end

@implementation TIMChatViewController

- (instancetype)initWithUserId:(NSString *)userId
{
    self = [super initWithUserId:userId];
    if (self) {
        ///设置聊天的数据源
        ///为了避免父类去预加载的时候数据源没有设置的问题,必须在初始化的时候设置好数据源代理
        self.dataSource = [[TIMChatData alloc]init];
    }
    return self;
}
- (void)dealloc{
    NSLog(@"TIMChatViewController已释放");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc]initWithTitle:@"收到消息" style:UIBarButtonItemStylePlain target:self action:@selector(receiveMessage)],
                                                [[UIBarButtonItem alloc]initWithTitle:@"聊天页面" style:UIBarButtonItemStylePlain target:self action:@selector(chat)]];
    // Do any additional setup after loading the view.
}
- (void)chat{
    TIMChatViewController *vc = [[TIMChatViewController alloc]initWithUserId:@"000000"];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)receiveMessage{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *text = [UIAlertAction actionWithTitle:@"收到文本消息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NCChatTextMessage *message = [NCChatTextMessage messageWith:@"测试文本" senderId:@"123456" date:[NSDate date]];
        message.status = NCChatMessageSending;
        [self.dataSource addMessages:message complete:^{
            [weakSelf finishSend];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                message.status = NCChatMessageSendFail;
            });
            
        }];
    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"收到图片消息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NCChatPhotoMessage *message = [NCChatPhotoMessage messageWith:nil previewSize:CGSizeMake(100, 180) senderId:@"123456" date:[NSDate date]];
        message.status = NCChatMessageSending;
        [self.dataSource addMessages:message complete:^{
            [weakSelf finishSend];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                message.status = NCChatMessageSendFail;
            });
            
        }];

    }];
    UIAlertAction *audio = [UIAlertAction actionWithTitle:@"收到语音消息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NCChatAudioMessage *message = [NCChatAudioMessage messageWith:nil time:3 senderId:@"123456" date:[NSDate date]];

        [self.dataSource addMessages:message complete:^{
            [weakSelf finishSend];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                message.status = NCChatMessageSendFail;
            });
        }];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:text];
    [alert addAction:photo];
    [alert addAction:audio];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}
#pragma mark- 发送语音
- (void)audioCompleteFinishNotification:(NSNotification *)notification{
    ///发送语音信息
    NSString *duration = notification.userInfo[@"duration"];
    NSString *path = notification.userInfo[@"path"];
    
    NCChatAudioMessage *message = [NCChatAudioMessage messageWith:path time:[duration integerValue] senderId:self.userId date:[NSDate date]];
    
    
    __weak typeof(self) weakSelf = self;
    [self.dataSource addMessages:message complete:^{
        [weakSelf finishSend];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            message.status = NCChatMessageSendFail;
        });
    }];
    
}
#pragma mark- 消息重发
- (void)messageSendFailNotification:(NSNotification *)notification{
    ///收到消息发送的通知,要么处理,要么交给子类去处理
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *retry = [UIAlertAction actionWithTitle:@"重发" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NCChatMessage *message = notification.object;
        message.status = NCChatMessageSending;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            message.status = NCChatMessageSendSuccess;
        });
        
        
    }];
    UIAlertAction *del = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        ///要删除的消息
        NCChatAudioMessage *message = (NCChatAudioMessage*)notification.object;
        NSUInteger index = [self.dataSource.messages indexOfObject:message];
        ///删除消息
        [self.dataSource delectMessage:notification.object complete:^{
            [CATransaction begin];
            [self.chatTableView beginUpdates];
            
            [CATransaction setCompletionBlock: ^{
                [self scrollToBottom:YES];
                NSLog(@"动画结束");
            }];
            [self.chatTableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
            [self.chatTableView endUpdates];
            [CATransaction commit];
        }];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:retry];
    [alert addAction:del];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
}
#pragma mark- 发送图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    __weak typeof(self) weakSelf = self;
    
    UIImage *image = (UIImage*)info[@"UIImagePickerControllerOriginalImage"];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        CGSize size = [UIImage imageSizeWithImage:image];
        ///发送图片信息
        NCChatPhotoMessage *message = [NCChatPhotoMessage messageWith:image previewSize:size senderId:self.userId date:[NSDate date]];
        message.status = NCChatMessageSending;
        [self.dataSource addMessages:message complete:^{
            [weakSelf finishSend];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                message.status = NCChatMessageSendFail;
            });
            
        }];

    }];
}
#pragma mark- 发送文本
- (void)receiveKeyBoardSendClick:(NSNotification *)notification{
    [self chatInputViewSendText:self.chatInputView.inputView.text];
}
- (void)chatInputViewSendText:(NSString *)text{
    self.chatInputView.inputView.text = @"";
    __weak typeof(self) weakSelf = self;
    NCChatTextMessage *message = [NCChatTextMessage messageWith:text senderId:self.userId date:[NSDate date]];
    message.status = NCChatMessageSending;
    
    [self.dataSource addMessages:message complete:^{
        [weakSelf finishSend];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            message.status = NCChatMessageSendFail;
        });
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        
    }
    return cell;
}

@end
